package com.sunny;

public class QuickSort2 {

    public void sort(int[] arr, int start, int end) {
        if (start > end) {
            return;
        }
        int p = partition(arr, start, end);
        sort(arr, start, p - 1);
        sort(arr, p + 1, end);
    }

    public int partition(int[] arr, int start, int end) {
        if (start == end) {
            return start;
        }
        int ind = start;
        int pivot = arr[end];
        for (int i = start; i < end; i++) {
            if (arr[i] < pivot) {
                if (i != ind) {
                    swap(arr, ind, i);
                }
                ind++;
            }
        }
        if (ind != end) {
            swap(arr, ind, end);
        }
        return ind;
    }

    private void swap(int[] arr, int i, int j) {
        arr[i] = arr[i] + arr[j];
        arr[j] = arr[i] - arr[j];
        arr[i] = arr[i] - arr[j];
    }

    public static void main(String[] args) {
        QuickSort2 quickSort2 = new QuickSort2();
        int[] arr = {2,1,8,5,3,9,0,2};
        quickSort2.sort(arr, 0, arr.length - 1);
        System.out.println();
        for (int i = 0; i < arr.length; i++) {
            if (i != 0) {
                System.out.print(" ");
            }
            System.out.print(arr[i]);
        }
    }

}
